package com.bjsxt.config.exception;

import com.bjsxt.vo.AjaxResult;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @RestControllerAdvice--统一异常处理，组件注解，使得其他类可以被扫描被发现
 * @ClassName GlobalExceptionHandler
 * @Description TODO
 * @Author xyx
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * MethodArgumentNotValidException如果页面传参是json对象且为空触发该方法
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public AjaxResult jsonErrorHandler(MethodArgumentNotValidException e) {
        return getAjaxResult(e.getBindingResult());
    }

    /**
     * MethodArgumentNotValidException如果页面传参是json对象且为空触发该方法
     *
     * @param e
     * @return
     */
    public AjaxResult jsonErrorHandler(BindException e) {
        return getAjaxResult(e.getBindingResult());
    }


    /**
     * 获取错误信息方法【抽象】
     *
     * @param bindingResult 用于实体类校验信息返回结果绑定
     * @return
     */
    private AjaxResult getAjaxResult(BindingResult bindingResult) {
        List<Map<String, Object>> list = new ArrayList<>();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        for (ObjectError error : allErrors) {
            Map<String, Object> map = new HashMap<>();
            map.put("defaultMessage", error.getDefaultMessage());
            map.put("objectName", error.getObjectName());
            FieldError fieldError = (FieldError) error;
            map.put("field", fieldError.getField());
            list.add(map);
        }
        return AjaxResult.fail("后端数据校验异常", list);
    }


}
